package exp7;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class MyKeyListener extends KeyAdapter{
	public void keyTyped(KeyEvent e){
		char c =e.getKeyChar();
		if(!(c>=KeyEvent.VK_0&&c<= KeyEvent.VK_9)){
			e.consume();
		}
	}
}
class MyMouseListener extends MouseAdapter{
	public void mouseEntered(MouseEvent e){
		JButton b = (JButton) e.getSource();
		b.setText("*");

	}
	public void mouseExited(MouseEvent e){
		JButton b = (JButton) e.getSource();
		b.setText("");
	}
}
public class Exp7_1 extends JFrame implements ActionListener{
	int rows = 5,cols = 4;
	JTextField rowTf = new JTextField(""+rows);
	JTextField colTf = new JTextField(""+cols);
	JPanel center = new JPanel();

	MyKeyListener keyListener = new MyKeyListener();
	MyMouseListener mouseListener = new MyMouseListener();

	void addButtons(){
		center.setLayout(new GridLayout(rows,cols,2,2));
		for(int i=0;i<rows;i++){
			for(int j= 0;j<cols;j++){
				JButton b = new JButton();
				b.addMouseListener(mouseListener);
				center.add(b);
			}
		}
	}
	void initUI(){
		JPanel top  =new JPanel(new GridLayout(1,4));
		top.add(new JLabel("行数："));
		rowTf.addActionListener(this);
		rowTf.addKeyListener(keyListener);
		top.add(rowTf);

		top.add(new JLabel("列数："));
		colTf.addActionListener(this);
		colTf.addKeyListener(keyListener);
		top.add(colTf);

		this.addButtons();
		super.setLayout(new BorderLayout());
		super.add(top,BorderLayout.NORTH);
		super.add(center,BorderLayout.CENTER);
	}
	public void actionPerformed(ActionEvent e){
		if(e.getSource()==rowTf|| e.getSource()==colTf){
			rows= Integer.parseInt(rowTf.getText());
			cols= Integer.parseInt(colTf.getText());
			if(rows>10){
				rows=10;
				rowTf.setText("10");
			}else if (rows<1){
				rows=1;
				rowTf.setText("1");

			}
			if(cols>10){
				cols=10;
				colTf.setText("10");
			}else if(cols<1){
				cols=1;
				colTf.setText("1");
			}
		}
		center.removeAll();
		this.addButtons();
		center.validate();
		center.repaint();

	}
	public static void main(String[] args) {
		Exp7_1 t =new Exp7_1();
		t.initUI();
		t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		t.setSize(600,400);
		t.setVisible(true);

	}
}
